﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using EHTSaleManager.Code.Entity;
using EHTSaleManager.Code.BLL;
using EHTSaleManager.Code.Utility;
using System.IO;
using System.Collections.Specialized;
using System.Web.Profile;

namespace EHTSaleManager.UIAdmin
{
    public partial class AdminOrderDetail : System.Web.UI.Page
    {
        public String CustomerID = "";
        public Int32 OrderID = -1;
        public Int32 OrderState = HangSo.ORDER_STATE_APPENDING;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["OrderID"] != null)
            {
                try
                {
                    OrderID = Int32.Parse(Request.QueryString["OrderID"].ToString());
                }
                catch (Exception ex)
                {
                    OrderID = -1;
                }
            }
            if (!Page.IsPostBack)
            {
                GetOrder();
                if (OrderState == HangSo.ORDER_STATE_APPENDING)
                {
                    btnShip.Visible = true;
                    btnSave.Visible = false;
                }
                else
                {
                    btnShip.Visible = false;
                    if (OrderState == HangSo.ORDER_STATE_SHIPPED)
                    {
                        btnSave.Visible = false;
                    }
                    else
                    {
                        btnSave.Visible = true;
                    }
                }
            }

        }

        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;
            string sExtendsion = ".gif|.GIF|.jpg|.JPG|.png|.PNG|.bmp|.BMP|.jpeg|.JPEG";

            try
            {
                if (this.fuBillUpload.HasFile)
                {
                    if (sExtendsion.IndexOf(Path.GetExtension(fuBillUpload.PostedFile.FileName)) < 0)
                    {
                        isSuccess = false;
                        message = "Upload picture only.";
                    }
                }
                else
                {
                    if (ViewState["BillUploadedUrl"].ToString() == "")
                    {
                        isSuccess = false;
                        message = "Please browse file bill to upload.";
                    }
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
            }
            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }

        private void GetOrder()
        {
            Order theOrders = OrderProvider.GetOrderByOrderID(OrderID);
            if (theOrders == null)
                Response.Redirect("AdminOrders.aspx");
            else
            {
                ViewState["OrderID"] = theOrders.OrderID;
                ViewState["OrderState"] = theOrders.OrderState;
                ViewState["BillUploadedUrl"] = theOrders.BillPictureUrl;
                lbCustomerName.Text = theOrders.ReceivedName.ToString();
                lbAddress.Text = theOrders.ReceivedAddress.ToString();
                lbCity.Text = theOrders.ReceivedCity.ToString();
                Region theRegions = RegionProvider.GetRegionByRegionID(Int32.Parse(theOrders.ReceivedRegionID.ToString()));
                lbRegion.Text = theRegions.RegionName;
                lbPhone.Text = theOrders.ReceicedPhone.ToString();
                lbCreatedDate.Text = theOrders.CreateDate.ToString();
                lbRequiredDate.Text = theOrders.RequireDate.ToString();
                lbTotalAmount.Text = theOrders.TotalAmount.ToString();
                lbServiceCost.Text = theOrders.ServiceCost.ToString();
                if (theOrders.BillPictureUrl.ToString().Trim() != "")
                {
                    imgBill.ImageUrl = "~/ImageDatas/BillScaned/" + theOrders.BillPictureUrl.ToString();
                }
                // Bắt trạng thái có hóa đơn chưa để hiện nút download hóa đơn
                if (imgBill.ImageUrl.ToString().Trim() == "")
                {
                    // Ẩn nút download
                    lbtnDownloadBill.Visible = false;
                }
                else
                {
                    // Hiện nút download
                    lbtnDownloadBill.Visible = true;
                }
                OrderState = theOrders.OrderState;
                if (OrderID != -1)
                {
                    DataSet dsOrderDetails = OrderDetaiProvider.GetOrderDetailByOrderID(OrderID);
                    rOrderDetails.DataSource = dsOrderDetails;
                    rOrderDetails.DataBind();
                }
            }
        }

        private void DownloadFile(FileInfo fname)
        {
            NameValueCollection imageExtensions = new NameValueCollection();
            imageExtensions.Add(".jpg", "image/jpeg");
            imageExtensions.Add(".gif", "image/gif");
            imageExtensions.Add(".png", "image/png");
            imageExtensions.Add(".jpeg", "image/jpeg");
            imageExtensions.Add(".bmp", "image/bmp");
            if (imageExtensions.AllKeys.Contains(fname.Extension))
            {
                Response.ContentType = imageExtensions.Get(fname.Extension);
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + fname.Name);
                Response.TransmitFile(fname.FullName);
                Response.End();
            }
        }


        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UIAdmin/AdminOrders.aspx");
        }

        // Sự kiện cho nút Update Bill
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {
                if (OrderID != -1)
                {
                    if (this.fuBillUpload.HasFile)
                    {
                        String fileName = fuBillUpload.PostedFile.FileName;
                        String fileType = Path.GetExtension(fileName);
                        String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                        string str = Server.MapPath("~/");
                        str += "ImageDatas\\BillScaned\\";
                        DirectoryInfo directory = new DirectoryInfo(str);

                        if (!directory.Exists)
                        {
                            DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                            if (!drt.Exists)
                            {
                                directory = new DirectoryInfo(Server.MapPath("~/"));

                                directory = directory.CreateSubdirectory("ImageDatas");

                            }
                            directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                            directory = directory.CreateSubdirectory("BillScaned");
                        }
                        // Lưu file lên server
                        fuBillUpload.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//BillScaned//" + newFileName);

                        // Update trạng thái của order thành Shipped (trạng thái 3)
                        OrderProvider.UpdateShipAndBillOfOrderByOrderID(OrderID, HangSo.ORDER_STATE_SHIPPED, newFileName, HangSo.UPDATE_BILL);

                        // Cập nhật Acount balance

                        Order theOrder = new Order();
                        float TotalOrderAmount = 0;
                        theOrder = OrderProvider.GetOrderByOrderID(OrderID);
                        if (theOrder != null)
                        {
                            TotalOrderAmount = float.Parse(theOrder.TotalAmount.ToString().Trim());
                            CustomerID = theOrder.CustomerID;
                            DataSet dsUser = AdminProvider.GetUserByUserId(CustomerID);
                            ProfileBase theProfile = ProfileBase.Create(dsUser.Tables[0].Rows[0]["Username"].ToString());
                            float toltalAccountCurrent = float.Parse(theProfile.GetPropertyValue("ToltalAccount").ToString()); // tổng tài khoản hiện tại
                            float toltalAccountNow = TotalOrderAmount + toltalAccountCurrent; // tổng tài khoảng thay thế
                            theProfile.SetPropertyValue("ToltalAccount", toltalAccountNow);
                            theProfile.Save();

                            // update AccountBalance trong bang CurrentBalance or LastBalance
                            //Start
                            AccountBalanceProvider.UpdateAccountBalanceByCustomerID(CustomerID, TotalOrderAmount, Convert.ToInt32(theProfile.GetPropertyValue("ServiceLevelID")));
                            // End
                        }
                    }

                }
                Response.Redirect("~/UIAdmin/AdminOrders.aspx");
            }
        }
        // Sự kiện nút Ship Order
        protected void btnShip_Click(object sender, EventArgs e)
        {
            if (OrderID != 1)
            {
                // Update trạng thái của hóa đơn về Shipping (trạng thái 2)
                OrderProvider.UpdateShipAndBillOfOrderByOrderID(OrderID, HangSo.ORDER_STATE_SHIPPING, String.Empty, HangSo.UPDATE_SHIPPING);
            }
            Response.Redirect("~/UIAdmin/AdminOrders.aspx");
        }

        // Sự kiện cho Linkbutton Download Bill
        protected void lbtnDownloadBill_Click(object sender, EventArgs e)
        {
            String filename = Server.MapPath("~/ImageDatas/BillScaned/") + (imgBill.ImageUrl.ToString()).Substring(imgBill.ImageUrl.ToString().LastIndexOf("/") + 1, imgBill.ImageUrl.ToString().Length - imgBill.ImageUrl.ToString().LastIndexOf("/") - 1);
            FileInfo fImage = new FileInfo(filename);

            Boolean kiemtra = File.Exists(filename);
            Console.WriteLine(kiemtra.ToString());
            if (kiemtra == true)
            {
                DownloadFile(fImage);
            }          
            
        }
    }
}